package com.xzx.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * Hello world!
 */
public class App {

    private String connectString = "localhost:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeperClient;

    @Before
    public void init() throws IOException {
        zooKeeperClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("process:" + event);
                String path = event.getPath();
                if ("/".equals(path)) {
                    System.out.println(event.getType());
                    try {
                        zooKeeperClient.getChildren("/", true); //监听器用完一次就废了，得需要重新注册监听
                        List<String> children = zooKeeperClient.getChildren(path, true);
                        for (String str : children) {
                            System.out.println(str);
                        }
                        System.out.println("==========end");
                    } catch (KeeperException | InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    @Test
    public void create() throws KeeperException, InterruptedException {
        // 返回创建后的节点路径
        String path = zooKeeperClient.create("/xzx", "xzx".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }

    @Test
    public void getChildNode() throws KeeperException, InterruptedException {
        List<String> children = zooKeeperClient.getChildren("/", true);
        for (String str : children) {
            System.out.println(str);
        }

        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat stat = zooKeeperClient.exists("/xxx", false);
        System.out.println(stat==null?"不存在":"存在");
    }
}
